﻿using System;
using System.Collections.Generic;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Client;
using NLog;

namespace TfsGiggle.Core
{
    /// <summary>
    /// Miscellaneous Tfs functions
    /// </summary>
    public static class TfsUtil
    {
        private static Logger _logger = LogManager.GetCurrentClassLogger();
        private const string NotificationTag = "TfsGiggleCheckinEvent";

        /// <summary>
        /// Unsubscribes to TfsGiggle notifications
        /// </summary>
        /// <param name="tfsUri"></param>
        /// <param name="subscriptionIds"></param>
        public static void UnSubscribeToCheckinEvent(Uri tfsUri, int[] subscriptionIds)
        {
            _logger.Trace("tfsUri:{0}", tfsUri);

            // http://blogs.msdn.com/b/taylaf/archive/2010/01/26/retrieve-the-list-of-team-project-collections-from-tfs-2010-client-apis.aspx
            using (var tfsConfigurationServer = TfsConfigurationServerFactory.GetConfigurationServer(tfsUri))
            {
                tfsConfigurationServer.EnsureAuthenticated();
                var tpcService = tfsConfigurationServer.GetService<ITeamProjectCollectionService>();
                foreach (var tfs in tpcService.GetCollections())
                {
                    _logger.Trace("tfsUri:{0} Name:{1}", tfsUri, tfs.Name);
                    var eventService = tfsConfigurationServer.GetTeamProjectCollection(tfs.Id).GetService<IEventService>();
                    for (int i = 0; i < subscriptionIds.Length; i++)
                    {
                        eventService.UnsubscribeEvent(subscriptionIds[i]);
                    }
                }
            }
        }

        /// <summary>
        /// Subscribes to TfsGiggle notification
        /// </summary>
        /// <param name="tfsUri"></param>
        /// <param name="subscriptionUri"></param>
        /// <returns></returns>
        public static int[] SubscribeToCheckinEvents(Uri tfsUri, Uri subscriptionUri)
        {
            _logger.Trace("tfsUri:{0} subscriptionUri:{1}", tfsUri, subscriptionUri);

            List<int> subscriptions = new List<int>();
            // http://blogs.msdn.com/b/taylaf/archive/2010/01/26/retrieve-the-list-of-team-project-collections-from-tfs-2010-client-apis.aspx
            using (var tfsConfigurationServer = TfsConfigurationServerFactory.GetConfigurationServer(tfsUri))
            {
                tfsConfigurationServer.EnsureAuthenticated();
                var tpcService = tfsConfigurationServer.GetService<ITeamProjectCollectionService>();
                foreach (var tfs in tpcService.GetCollections())
                {
                    var eventService = tfsConfigurationServer.GetTeamProjectCollection(tfs.Id).GetService<IEventService>();

                    // Delete existing subscriptions
                    var existingSubscriptions = eventService.GetEventSubscriptions(Environment.UserName, NotificationTag);
                    {
                        foreach (var subscription in existingSubscriptions)
                        {
                            eventService.UnsubscribeEvent(subscription.ID);
                        }
                    }

                    // Create new subscription
                    var deliveryPreference = new DeliveryPreference();
                    deliveryPreference.Address = subscriptionUri.AbsoluteUri;
                    deliveryPreference.Schedule = DeliverySchedule.Immediate;
                    deliveryPreference.Type = DeliveryType.Soap;
                    var subscriptionId = eventService.SubscribeEvent(System.Environment.UserDomainName + "\\" + System.Environment.UserName, "CheckinEvent", "", deliveryPreference, NotificationTag);
                    subscriptions.Add(subscriptionId);
                    _logger.Trace("tfsUri:{0} Name:{1} Subscription:{2}", tfsUri, tfs.Name, subscriptionId);

                    // Announce the tfsGiggle uri to all clients via the tfs project collection registry
                    var registry = tfsConfigurationServer.GetTeamProjectCollection(tfs.Id).GetService<ITeamFoundationRegistry>();

                    // Trial and error
                    registry.SetValue("/Service/Registration/RegistrationExtendedAttribute/TfsGiggle/Uri", subscriptionUri);

                }
            }
            return subscriptions.ToArray();
        }
    }
}